package com.itheima.reggie.service.impI;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpI extends ServiceImpl<SetmealMapper, Setmeal>implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //前面可以用super或this;保存套餐基本信息
        save(setmealDto);
        //补全套餐与菜品的关系
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        //保存套餐和菜品的信息
        setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Setmeal::getId,ids);
        wrapper1.eq(Setmeal::getStatus,1);
        int count = count(wrapper1);
        if (count>0){
            throw new CustomerException("有正在出售的套餐,不能删除");
        }
        for (Long id : ids) {
            removeById(id);
        }
        LambdaQueryWrapper<SetmealDish> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.in(SetmealDish::getId,ids);
        for (Long id : ids) {
            setmealDishService.removeById(id);
        }
    }
}
